const app = getApp();
import { searchList, dynamiGive_option, townActivity_list, activityGive_option } from "../../../api/homePage"
import { baseUrl } from "../../../api/request"
import { getStorage } from "../../../utils/localStorage"
import { getMapDistance } from "../../../utils/address"
Page({
    data: {
        navData: {
            level: 2,
            title: "搜索"
        },
        baseUrl: baseUrl,
        user: getStorage('user'),
        scFlag: true,
        navHeight: 0,
        navTop: 0,
        navObj: 0,
        navWeight: 0,
        swiper: {
            autoplay: true, //自动切换
            dots: true, //指示点
            dotsColor: "#ffffff", //指示点颜色
            dotsActiveColor: "#4646A0", //选中指示点颜色
            circular: true, //衔接滑动
            duration: 3000, //滑动动画时长
            boxFlag: false,
        },
        mapArr: [
            {
                id: 1,
                latitude: 29.115004,
                longitude: 119.623134,
                name: '浙江蘑菇云数据科技有限公司',
                desc: '我现在的位置',
                iconPath: "../../../image/address.png",
                width: 30,
                height: 30,
            }
        ],
        soFlag: false,
        listQuery: {
            userId: getStorage("user"),
            title: "",
            pageSize: 10,
            pageNum: 1,
        },
        total: 0, //列表总页数
        showPull: true, //上拉加载更多状态
        leftList: [], //列表左边显示数据
        rightList: [],//列表右边显示数据
        listType: true, //列表展示数据类型 true:用户动态,false:活动动态
        latlng: getStorage("latLng"),
        pageTop: app.globalData.navHeight + app.globalData.navTop,
    },

    onLoad(options) {
        this.setData({
            "listQuery.userId": getStorage("user").id
        });
        app.globalData.detailPageType = "搜索";  //详情页类型
        if (JSON.stringify(options) != "{}") {
            let item = JSON.parse(decodeURIComponent(options.item));
            this.setData({
                listType: false,
                "listQuery.townShipName": item.townName
            });
            this.getActivityList();
        } else {
            this.setData({
                listType: true
            });
            this.getDynamicList();
        }
    },
    onShow() {
        //动态点赞静态处理
        let dynamicId = app.globalData.dynamicId, dynamicGive = app.globalData.dynamicGive, dynamicGiveNum = app.globalData.dynamicGiveNum;
        if (dynamicId) {
            let indexFlag = this.data.leftList.findIndex(item => { return item.id === dynamicId }), index = null, value = null, num = null;
            if (indexFlag === -1) {
                index = this.data.rightList.findIndex(item => { return item.id === dynamicId });
                value = "rightList[" + index + "].likeState";
                num = "rightList[" + index + "].likeNumber";
            } else {
                index = this.data.leftList.findIndex(item => { return item.id === dynamicId });
                value = "leftList[" + index + "].likeState";
                num = "leftList[" + index + "].likeNumber";
            };
            this.setData({
                [value]: dynamicGive === 1 ? true : false,
                [num]: dynamicGiveNum,
            });

        };
        //活动点赞静态处理
        let activityId = app.globalData.activityId,
            activityGive = app.globalData.activityGive,
            activityGiveNum = app.globalData.activityGiveNum;
        if (activityId) {
            let indexFlag = this.data.leftList.findIndex(item => { return item.id === activityId }), index = null, value = null, num = null;
            if (indexFlag === -1) {
                index = this.data.rightList.findIndex(item => { return item.id === activityId });
                value = "rightList[" + index + "].likeState";
                num = "rightList[" + index + "].likeNumber";
            } else {
                index = this.data.leftList.findIndex(item => { return item.id === activityId });
                value = "leftList[" + index + "].likeState";
                num = "leftList[" + index + "].likeNumber";
            };
            this.setData({
                [value]: activityGive === 1 ? true : false,
                [num]: activityGiveNum,
            });

        };
    },
    //用户动态列表数据
    getDynamicList() {
        let that = this.data;
        searchList(that.listQuery).then(res => {
            if (!res.data.rows || res.data.rows.length === 0) {
                this.setData({
                    leftList: [],
                    rightList: [],
                });
            } else {
                let leftArr = [], rightArr = [];
                res.data.rows.forEach((item, index) => {
                    item.imageScale = item.imageScale.split(",");
                    item.distance = getMapDistance(that.latlng.lat, that.latlng.lng, item.latitude, item.longitude);
                    if (index % 2 === 0) {
                        leftArr.push(item);
                    } else {
                        rightArr.push(item);
                    };
                });
                this.setData({
                    leftList: [...that.leftList, ...leftArr],
                    rightList: [...that.rightList, ...rightArr],
                    total: Math.ceil(res.data.total / that.listQuery.pageSize)
                });
            };
        });

    },
    //活动列表数据
    getActivityList() {
        let that = this.data;
        townActivity_list(that.listQuery).then(res => {
            if (!res.data.rows || res.data.rows.length === 0) {
                this.setData({
                    leftList: [],
                    rightList: []
                });
            } else {
                let leftArr = [], rightArr = [];
                res.data.rows.forEach((item, index) => {
                    item.imageScale = item.imageScale.split(",");
                    item.distance = getMapDistance(that.latlng.lat, that.latlng.lng, item.latitude, item.longitude);
                    if (index % 2 === 0) {
                        leftArr.push(item);
                    } else {
                        rightArr.push(item);
                    };
                });
                this.setData({
                    leftList: leftArr,
                    rightList: rightArr,
                });
            };
        });
    },
    //搜索事件
    searchInput(e) {
        const val = e.detail.value;
        this.setData({
            leftList: [],
            rightList: [],
            "listQuery.title": val,
            "listQuery.pageNum": 1,
        });
        //区分是动态列表还是活动列表
        if (this.data.listType) {
            this.getDynamicList();
        } else {
            this.getActivityList();
        };
    },
    //列表详情点击事件
    listTap(e) {
        const item = e.currentTarget.dataset.item;
        //区分是动态列表还是活动列表
        if (this.data.listType) {
            wx.navigateTo({
                url: '/pagesShouYe/pages/listDetail/index?id=' + item.id,
            })
        } else {
            wx.navigateTo({
                url: '/pagesShouYe/pages/bnnerDetailMore/index?id=' + item.id,
            });
        };
    },
    //用户动态点赞或取消点赞事件
    commentClick(e) {
        let that = this.data,
            item = e.currentTarget.dataset.item,
            index = e.currentTarget.dataset.index,
            title = e.currentTarget.dataset.title,
            flag = !item.likeState ? true : false;
        if (this.data.listType) {
            dynamiGive_option({ userId: that.user.id, dynamicsId: item.id, state: flag }).then(res => {
                let state = "";
                let num = "";
                if (res.data.code === 200) {
                    wx.showToast({
                        icon: 'none',
                        title: res.data.msg,
                        duration: 1000,
                    });
                    if (title === "leftList") {
                        state = "leftList[" + index + "].likeState";
                        num = "leftList[" + index + "].likeNumber";
                    } else if (title === "rightList") {
                        state = "rightList[" + index + "].likeState";
                        num = "rightList[" + index + "].likeNumber";
                    };
                    this.setData({
                        [state]: flag,
                        [num]: !item.likeState ? item.likeNumber + 1 : item.likeNumber - 1
                    });
                };
            });
        } else {
            activityGive_option({ userId: that.user.id, activityId: item.id, state: flag }).then(res => {
                let state = "";
                let num = "";
                if (res.data.code === 200) {
                    wx.showToast({
                        icon: 'none',
                        title: res.data.msg,
                        duration: 1000,
                    });
                    if (title === "leftList") {
                        state = "leftList[" + index + "].likeState";
                        num = "leftList[" + index + "].likeNumber";
                    } else if (title === "rightList") {
                        state = "rightList[" + index + "].likeState";
                        num = "rightList[" + index + "].likeNumber";
                    };
                    this.setData({
                        [state]: flag,
                        [num]: !item.likeState ? item.likeNumber + 1 : item.likeNumber - 1
                    });
                };
            });
        }
    },
    /* 上拉加载更多 */
    pullUp(e) {
        let that = this.data;
        if ((that.listQuery.pageNum + 1) <= that.total) {
            this.setData({
                showPull: false,
                "listQuery.pageNum": that.listQuery.pageNum += 1
            });
            this.getDynamicList();
        } else {
            this.setData({
                showPull: true
            });
        };
    },

    onReady() {

    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide() {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload() {

    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh() {

    },
    /**
     * 用户点击右上角分享
     */
    onShareAppMessage() {

    }
})